// 显示UI
figma.showUI(__html__, { width: 300, height: 200 });

// 存储当前选中的节点
let currentSelection = figma.currentPage.selection;

// 监听选择变化
figma.on("selectionchange", () => {
  currentSelection = figma.currentPage.selection;
});

// 递归收集节点元数据
function getNodeMetadata(node) {
  const metadata = {
    id: node.id,
    name: node.name,
    type: node.type,
    visible: node.visible,
    locked: node.locked,
    x: node.x,
    y: node.y,
    width: node.width,
    height: node.height,
    rotation: node.rotation,
    fills: node.fills,
    strokes: node.strokes,
    effects: node.effects,
    constraints: node.constraints,
  };

  // 特殊处理文本节点
  if (node.type === "TEXT") {
    metadata.characters = node.characters;
    metadata.fontSize = node.fontSize;
    metadata.fontName =
      typeof node.fontName === "string" ? node.fontName : node.fontName.family;
  }

  // 递归处理子节点
  if ("children" in node) {
    metadata.children = node.children.map((child) => getNodeMetadata(child));
  }

  return metadata;
}

// 处理来自UI的消息
figma.ui.onmessage = async (message) => {
  if (message.type === "export-json") {
    // 导出当前选中的节点元数据
    const layers = currentSelection.map((node) => getNodeMetadata(node));
    const result = {
      type: "figma",
      created: new Date().toISOString(),
      layers,
    };

    // 发送数据回UI
    figma.ui.postMessage({
      type: "export-data",
      data: result,
    });
  }
};
